from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from datetime import datetime, date
import os
import json
from selenium.webdriver.common.by import By

def daily_sign_in():
    """执行每日签到任务"""
    try:
        # 浏览器设置
        chrome_options = Options()
        # chrome_options.add_argument("--start-maximized")  # 最大化窗口
        ## 无头模式
        chrome_options.add_argument("--headless")
        
        # 初始化浏览器
        driver = webdriver.Chrome(options=chrome_options)

        # 打开登录页面
        driver.get("https://neworld.cloud/auth/login")
        print("已打开登录页面...")

        # 自动登录
        driver.implicitly_wait(10)
        try:
            with open('config.json', 'r', encoding='utf-8') as f:
                config = json.load(f)
            driver.find_element("id", "email").send_keys(config['email'])
            driver.find_element("id", "passwd").send_keys(config['password'])
        except FileNotFoundError:
            print("错误: 找不到配置文件config.json")
            return False
        except json.JSONDecodeError:
            print("错误: 配置文件格式不正确")
            return False
        except KeyError:
            print("错误: 配置文件中缺少必要的email或password字段")
            return False
            
        driver.find_element("id", "login-dashboard").click()
        print("正在自动登录...")
        time.sleep(5)  # 等待登录完成

        try:
            # 定位并点击签到按钮
            clock_icon = driver.find_element("id", "check-in")
            driver.execute_script("arguments[0].click();", clock_icon)
            time.sleep(3)  # 等待点击完成
            print("签到成功!")
            
            # 记录签到时间
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            print(f"签到时间: {current_time}")

        except Exception as e:
            print(f"签到按钮点击失败: {str(e)}")
            return False
            
        finally:
            driver.quit()
            
    except Exception as e:
        print(f"签到过程中出错: {str(e)}")
        return False
        
    return True

def get_last_sign_date():
    """获取上次签到日期"""
    if not os.path.exists("last_sign.txt"):
        return None
    with open("last_sign.txt", "r") as f:
        return f.read().strip()

def update_sign_date():
    """更新签到日期"""
    with open("last_sign.txt", "w") as f:
        f.write(str(date.today()))

def main():
    print("VPN自动签到服务已启动...")
    while True:
        try:
            current_date = date.today()
            last_sign = get_last_sign_date()
            
            if str(current_date) != last_sign:
                print(f"检测到新日期 {current_date}, 开始签到...")
                if daily_sign_in():
                    update_sign_date()
                    print("今日签到已完成!")
                else:
                    print("签到失败, 将在1小时后重试")
            
            # 每小时检查一次
            time.sleep(3600)
            
        except KeyboardInterrupt:
            print("\n服务正在停止...")
            break
        except Exception as e:
            print(f"服务运行出错: {str(e)}, 将在10分钟后重试")
            time.sleep(600)

if __name__ == "__main__":
    main()
